from datetime import datetime, timedelta


class DateHandler(object):
    @staticmethod
    def day_begin_end(times=None):
        times = datetime.now() if times is None else datetime.strptime(times, "%Y-%m-%d")
        start_time = times.strftime("%Y-%m-%d 00:00:00")
        end_time = times.strftime("%Y-%m-%d 23:59:59")
        return start_time, end_time

    @staticmethod
    def get_last_day(times=None):
        last_date = datetime.now() if times is None else datetime.strptime(times, "%Y-%m-%d")
        last_date = last_date - timedelta(days=1)
        return last_date.strftime("%Y-%m-%d")

    @staticmethod
    def today():
        times = datetime.now()
        return times.strftime("%Y-%m-%d")

    @staticmethod
    def now():
        times = datetime.now()
        return times.strftime("%Y-%m-%d %H:%M:%S")

    @staticmethod
    def weekday(times=None):
        times = datetime.now() if times is None else datetime.strptime(times, "%Y-%m-%d %H:%M:%S")
        return times.weekday()

    # 时间戳转换
    @staticmethod
    def date_int2str(timestamp):
        return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")

    # 两个时间比较, 结果是秒
    @staticmethod
    def time_diff(start_time, end_time):
        start_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        return (end_time - start_time).total_seconds()

    @staticmethod
    def get_this_month_start_end(times=None):
        now = datetime.now() if times is None else datetime.strptime(times, "%Y-%m-%d")
        # 本月第一天和最后一天
        this_month_start = datetime(now.year, now.month, 1)

        month = now.month + 1
        if month == 13:
            this_month_end = datetime(now.year + 1, 1, 1) - timedelta(days=1)
        else:
            this_month_end = datetime(now.year, now.month + 1, 1) - timedelta(days=1)
        return this_month_start, this_month_end

    def get_last_month_start_end(self, times=None):
        this_month_start, this_month_end = self.get_this_month_start_end(times)
        # 上月第一天和最后一天
        last_month_end = this_month_start - timedelta(days=1)
        last_month_start = datetime(last_month_end.year, last_month_end.month, 1)
        return last_month_start.strftime("%Y-%m-%d"), last_month_end.strftime("%Y-%m-%d")


if __name__ == '__main__':
    s = DateHandler().get_last_month_start_end("2020-01-1")
    # s = s / 60
    print(s)

